package www13;

// 1. 定义一个命令接口
interface Command {
    void execute();
    void undo();
}

// 2. 具体的命令类 - 打开灯光
class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }

    @Override
    public void undo() {
        light.off();
    }
}

// 3. 具体的命令类 - 关闭灯光
class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.off();
    }

    @Override
    public void undo() {
        light.on();
    }
}

// 4. 接收者 - 灯光
class Light {
    public void on() {
        System.out.println("灯光已打开");
    }

    public void off() {
        System.out.println("灯光已关闭");
    }
}

// 5. 调用者 - 遥控器
class RemoteControl {
    private Command[] onCommands;
    private Command[] offCommands;
    private Command undoCommand;

    public RemoteControl() {
        onCommands = new Command[3];
        offCommands = new Command[3];
    }

    public void setCommand(int slot, Command onCommand, Command offCommand) {
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }

    public void pressButton(int slot) {
        onCommands[slot].execute();
        undoCommand = onCommands[slot];
    }

    public void pressUndoButton() {
        if (undoCommand != null) {
            undoCommand.undo();
        }
    }
}

// 6. 测试类 - 演示命令模式
public class Main { // 类名建议改为更合适的，如 CommandPatternDemo
    public static void main(String[] args) {
        Light livingRoomLight = new Light();
        Light kitchenLight = new Light();

        Command livingRoomLightOn = new LightOnCommand(livingRoomLight);
        Command livingRoomLightOff = new LightOffCommand(livingRoomLight);

        Command kitchenLightOn = new LightOnCommand(kitchenLight);
        Command kitchenLightOff = new LightOffCommand(kitchenLight);

        RemoteControl remoteControl = new RemoteControl();

        remoteControl.setCommand(0, livingRoomLightOn, livingRoomLightOff);
        remoteControl.setCommand(1, kitchenLightOn, kitchenLightOff);

        System.out.println("--- 按下客厅灯光打开按钮 ---");
        remoteControl.pressButton(0);

        System.out.println("--- 按下厨房灯光打开按钮 ---");
        remoteControl.pressButton(1);

        System.out.println("--- 按下撤销按钮 ---");
        remoteControl.pressUndoButton();
    }
}